//
//  CourseViewController.m
//  ECBBusinessCamp
//
//  Created by rimi on 16/6/27.
//  Copyright © 2016年 邓毕华. All rights reserved.
//

#import "CourseViewController.h"

#import "CourseCollectionViewCell.h"
#import "MoviePlayerViewController.h"

static NSString * const kCourseCollectionViewCellIdentifier = @"courseCollectionViewCell";

@interface CourseViewController ()<UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView * courseCollectionView; // 课程集合视图
@property (nonatomic, strong) UICollectionViewFlowLayout * layout; // 流式布局
@property (nonatomic, strong) NSMutableArray * dataSource; // 数据源
@property (nonatomic, assign) NSInteger pageNum; // 起始页数
@property (nonatomic, assign) NSInteger pageSize; // 每一页数据个数

@end

@implementation CourseViewController

#pragma mark 🌷🌷🌷life cycle🌷🌷🌷
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 添加视图
    [self.view addSubview:self.courseCollectionView];
    
    // POST参数初始化
    _pageNum = 0;
    _pageSize = 10;
    
    // 添加刷新
    [self addRefresh];
    
    // 数据加载
    [self loadData];
}
- (void)viewWillAppear:(BOOL)animated {
    // 自动布局
    [_courseCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(SCREEN_HEIGHT * 0.092);
        make.bottom.offset(SCREEN_HEIGHT * -0.09);
        make.left.offset(SCREEN_WIDTH * 0.195);
        make.right.offset(0);
    }];
}

#pragma mark 🌷🌷🌷UICollectionViewDataSource🌷🌷🌷
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CourseCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCourseCollectionViewCellIdentifier forIndexPath:indexPath];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:BASEURLAPPEND(_dataSource[indexPath.row][@"img"])]];
    cell.titleLabel.text = _dataSource[indexPath.row][@"name"];
    cell.videoid = _dataSource[indexPath.row][@"id"];
    [cell clickBackForStartLearBlock:^(NSString *lessonID) {
        UIAlertView *loading = [[UIAlertView alloc] initWithTitle:@"提示" message:@"视频正在加载中" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [loading show];
        [[NetWorkTools sharedTools] requestMethod:POST URL:sid(url(@"front_video!videoList.action")) parameters:@{@"token":[[NSUserDefaults standardUserDefaults] objectForKey:@"token"],@"id":lessonID,@"uid":[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]} finish:^(id responseObject, NSError *error) {
            if ([responseObject[@"status"] intValue] == 104) {
                NSLog(@"重复登陆");
            } else if ([responseObject[@"status"] intValue] == 1) {
                //判断有没有视频  listName.cout
                NSArray *videoArray = responseObject[@"data"][@"listName"];
                if (videoArray.count == 0) {
                    //提示没有课程
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [loading dismissWithClickedButtonIndex:0 animated:YES];
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该课程还没有可播放的教学视频" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                        [alert show];
                    });
                } else {
                    //有视频跳转操作
                    [loading dismissWithClickedButtonIndex:0 animated:YES];
                    //取视频的url地址存起
                    NSMutableArray *urlList = [@[] mutableCopy];
                    NSMutableArray *idList = [@[] mutableCopy];
                    for (int i = 0; i < videoArray.count; i ++) {
                        [urlList addObject:url([EncryptTool decodeString:videoArray[i][@"url"]])];
                        [idList addObject:videoArray[i][@"id"]];
                    }
                    //切换到视频操作界面
                    MoviePlayerViewController *movieVc = [MoviePlayerViewController new];
                    movieVc.playerListArray = urlList;
                    movieVc.playerListIDArray = idList;
                    movieVc.lessonID = lessonID;
                    
                    [self presentViewController:movieVc animated:YES completion:nil];
                }
            }
        }];
    }];
    
    return cell;
}

#pragma mark 🌷🌷🌷private methods🌷🌷🌷
- (void)addRefresh {
    // 添加上拉刷新
    _courseCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _pageNum = 0;
        [self.dataSource removeAllObjects];
        [self loadData];
    }];
    // 添加下拉加载更多
    _courseCollectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        if ((_pageNum + 1) * _pageSize > _dataSource.count) {
            [MBProgressHUD showError:@"没有更多数据"];
            [_courseCollectionView.mj_footer endRefreshing];
            return ;
        }
        _pageNum += 1;
        [self loadData];
    }];
}
- (void)loadData {
    NSMutableDictionary * parmerters = [NSMutableDictionary dictionary];
    [parmerters setObject:@(_pageNum) forKey:@"pageNum"];
    [parmerters setObject:@(_pageSize) forKey:@"numPerPage"];
    [[NetTool sharedTool] requestMethod:POST loadingMsg:@"加载中..." url:BASEURLAPPEND(PERSONALHOMEPAGE_COURSE_URL) parameters:parmerters finish:^(id responseObject, NSError *error) {
        NSLog(@"%@", responseObject);
        if (!error) {
            [MBProgressHUD showSuccess:@"加载完成！"];
            [self.dataSource addObjectsFromArray:responseObject[@"data"]];
            [_courseCollectionView reloadData];
        } else {
            [MBProgressHUD showError:[[NSString stringWithFormat:@"%@", error] containsString:@"The request timed out."] ? @"登录超时" : @"I don't know"];
        }
        [_courseCollectionView.mj_header endRefreshing];
        [_courseCollectionView.mj_footer endRefreshing];
    }];
}

#pragma mark 🌷🌷🌷getters and setters🌷🌷🌷
- (UICollectionViewFlowLayout *)layout {
    if (!_layout) {
        _layout = [[UICollectionViewFlowLayout alloc] init];
        _layout.itemSize = CGSizeMake(SCREEN_WIDTH * 0.35, SCREEN_WIDTH * 0.3 * 0.91);
        _layout.minimumInteritemSpacing = 10;
        _layout.minimumLineSpacing = 50;
        _layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _layout.sectionInset = UIEdgeInsetsMake(30, 50, 10, 50);
    }
    return _layout;
}
- (UICollectionView *)courseCollectionView {
    if (!_courseCollectionView) {
        _courseCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:self.layout];
        _courseCollectionView.backgroundColor = [UIColor whiteColor];
        
        // 设置数据源
        _courseCollectionView.dataSource = self;
        
        // 注册单元格
        [_courseCollectionView registerClass:[CourseCollectionViewCell class] forCellWithReuseIdentifier:kCourseCollectionViewCellIdentifier];
    }
    return _courseCollectionView;
}
- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

@end
